package com.example.mo.allfind.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;

import com.example.mo.allfind.ui.callback.HeadCallBack;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by ZYF on 2017/3/28.
 */
public class HttpDownload {
    private Context context;

    public HttpDownload(Context context) {
        this.context = context;
    }

    public void download(String url,final HeadCallBack back) {
        //Target
        Target target = new Target(){

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                String imageName = "head.jpg";

                File filePath = new File(App.IMAGE_FILE_PATH);
                if(!filePath.exists()){
                    filePath.mkdirs();
                }
                File file = new File(App.IMAGE_FILE_PATH+imageName);
                if(file.exists()){
                    try {
                        file.delete();
                        file.createNewFile();
                        FileOutputStream ostream = null;
                        ostream = new FileOutputStream(file);
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                        ostream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                back.success();
            }
            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        //Picasso下载
        Picasso.with(context).load(url).into(target);
    }
}

